package cn.anc.aonicardv.module.ui.recorder;

import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ffmpeg.player.RtspPlayer;
import com.ffmpeg.player.RtspPlayerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import cn.anc.aonicardv.Constant;
import cn.anc.aonicardv.MyApplication;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.R2;
import cn.anc.aonicardv.bean.PhotoBean;
import cn.anc.aonicardv.bean.VideoBean;
import cn.anc.aonicardv.event.DestroyMapEvent;
import cn.anc.aonicardv.event.ScreenDisplayEvent;
import cn.anc.aonicardv.manager.CheckUpdatesVersionManager;
import cn.anc.aonicardv.module.ui.base.BaseActivity;
import cn.anc.aonicardv.net.download.DownLoadCallBack;
import cn.anc.aonicardv.net.download.DownLoadManager;
import cn.anc.aonicardv.param.ParamManager;
import cn.anc.aonicardv.util.ActivityUtils;
import cn.anc.aonicardv.util.DateUtils;
import cn.anc.aonicardv.util.DeviceInfo;
import cn.anc.aonicardv.util.DeviceUtils;
import cn.anc.aonicardv.util.DialogUtils;
import cn.anc.aonicardv.util.GpsUtil;
import cn.anc.aonicardv.util.LogUtil;
import cn.anc.aonicardv.util.NetUtils;
import cn.anc.aonicardv.util.StringUtils;
import cn.anc.aonicardv.util.TrafficInfo;
import cn.anc.aonicardv.util.ui.CarSettingGuiHandler;
import cn.anc.aonicardv.util.ui.UIUtil;
import cn.anc.aonicardv.widget.CustomDialog;
import cn.anc.aonicardv.widget.WarningDialog;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.CarControlCommand;
import cn.anc.httpcontrolutil.CarControlSettings;
import cn.anc.httpcontrolutil.SocketUtils;
import cn.anc.httpcontrolutil.cache.CacheManager;
import rx.Subscription;

/**
 * Created by yangdai on 2017/5/23.
 */

public class RecorderActivity extends BaseActivity implements CarControl.OnHeartBeatCallBack, CarControl.OnNotificationHandler, CarControl.OnCardvThumbnailCallback, DialogInterface.OnKeyListener, View.OnClickListener, RtspPlayer.OnPlayStartListener,
        RtspPlayerView.OnSurfaceViewListener, CarControl.OnCarControlCallback {
    @BindView(R2.id.fl_player_root)
    FrameLayout playerRootFl;
    @BindView(R2.id.fl_player_container)
    FrameLayout playerContainerFl;

    @BindView(R2.id.rl_recorder_play)
    RelativeLayout rlRecorderPlay;


    @BindView(R2.id.ll_exit_fullscreen)
    LinearLayout exitfullScreenLl;
    @BindView(R2.id.layout_fullscreen_option)
    LinearLayout fullScreenOptionLayout;

    @BindView(R2.id.tv_fullscreen_video)
    TextView fullscreenVideoTv;
    @BindView(R2.id.tv_fullscreen_take_photo)
    TextView fullscreenTakePhotoTv;
    @BindView(R2.id.pb_recorder_video)
    ProgressBar recorderVideoPb;
    @BindView(R2.id.tv_recorder_album)
    TextView recorderAlbumTv;
    @BindView(R2.id.iv_sound_mic)
    ImageView soundRecordingMicIv;

    @BindView(R2.id.tv_sound_volume)
    TextView soundRecordingVolumeTv;
    @BindView(R2.id.iv_loading)
    ImageView loadingIv;
    @BindView(R2.id.tv_record_notication)
    TextView tvRecordnotication;
    @BindView(R2.id.tv_urgent)
    TextView tvUrgent;
    @BindView(R2.id.tv_speed)
    TextView tvSpeed;


    @BindView(R2.id.ll_recorder_clarity)
    LinearLayout llRecorderClarity;

    @BindView(R2.id.tv_recorder_clarity_high)
    TextView tveRcorderClarityHigh;

    @BindView(R2.id.tv_recorder_clarity_medium)
    TextView tveRcorderClarityMedium;

    @BindView(R2.id.tv_recorder_clarity_low)
    TextView tveRcorderClarityLow;

    public String downloadPath;
    public Subscription downloadSub;
    private RecorderDownloadCallBack recorderDownloadCallBack;
    private CarControlSettings.SettingItem settingItemMic;
    private CarControlSettings.SettingItem settingItemVolume;
    private Handler handler = new Handler();
    private CarControlCallback carControlCallback = new CarControlCallback();
    private ProgressDialog progressDialog;
    private WarningDialog warningDialog;
    public static int recordingProgress;
    public static int mProgress;

    private boolean isFirst = true;
    private HideOptionBtnRunnable hideOptionBtnRunnable;
    private HideOptionNotificatRunnable hideOptionNotificatRunnable;
    private boolean isResume;
    private static long destroyLastTime;
    private DialogUtils dialogUtils;
    private static boolean isSmallVideoRecording;
    private RtspPlayerView rtspPlayerView;
    private boolean rtspPlayerViewReady = false;
    private long startRecordTime;
    private long endRecordTime;
    //OPPO手机无法兼容，通过控制boolean逻辑强制加载横屏
    private float mSpeed = (float) 0.00;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_recorder);
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }


    @Override
    public void initVariable() {
        dialogUtils = new DialogUtils();
        progressDialog = dialogUtils.getProgressDialog(this);
        warningDialog = dialogUtils.getWarningDialog(this);
        recorderDownloadCallBack = new RecorderDownloadCallBack();
        hideOptionBtnRunnable = new HideOptionBtnRunnable();
        hideOptionNotificatRunnable = new HideOptionNotificatRunnable();
        rtspPlayerView = new RtspPlayerView(getApplication());
        rtspPlayerView.setRtspPlayerSurfaceListerner(this);
    }


    public static final int MSG_TOGGLE_SHARPNESS_TIME_OUT = 533;
    public static final int MSG_EXIT_TIME_OUT = 123;

    private String playUrl = null;

    public static final int MSG_RTSP_PLAY_STATE_TIME_OUT = 502;
    public static final int MSG_RTSP_PLAY_STATE_SUCCESS = 200;
    public static final int MSG_RTSP_PLAY_STATE_FAIL = 400;
    public static final int MSG_RTSP_PLAY_STATE_READY_PLAY = 100;
    public static final int MSG_RTSP_PLAY_STATE_REPLAY = 101;
    public static final int MSG_RTSP_PLAY_STATE_STOP = 102;
    private int mRtspPlayReloadNum = 0;
    private int mPlayTimeOut = 0;
    private int timeOut = 0;
    private boolean isTimeOut = false;
    private boolean isToggleTimeOut = false;
    private int toggleTimeOut = 0;

    @Override
    public void setListener() {
        progressDialog.setOnKeyListener(this);
        warningDialog.okTv.setOnClickListener(this);
        RtspPlayer.getInstance().setPlayListener(this);
        mHandler = new Handler(this.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {

                    case TrafficInfo.MSG_GET_NETSPEED:
                        if (null != tvSpeed) {
                            tvSpeed.setText(msg.obj + "kb/s");

                        }
                        break;

                    case MSG_TOGGLE_SHARPNESS_TIME_OUT:
                        toggleTimeOut++;
                        //设置超时时间为5秒
                        if (toggleTimeOut >= 5) {
                            isToggleTimeOut = true;
                            mHandler.removeMessages(MSG_TOGGLE_SHARPNESS_TIME_OUT);
                            LogUtil.e("llcTest0828", "---------MSG_TOGGLE_SHARPNESS_TIME_OUT----setRecorderClarity:" );
                            setRecorderClarity();
                            mHandler.sendEmptyMessage(MSG_RTSP_PLAY_STATE_REPLAY);
                        } else {
                            sendEmptyMessageDelayed(MSG_TOGGLE_SHARPNESS_TIME_OUT, 1000);
                        }
                        break;


                    case MSG_EXIT_TIME_OUT:
                        timeOut++;
                        //设置超时时间为5秒
                        if (timeOut >= 5) {
                            isTimeOut = true;
                            mHandler.removeMessages(MSG_EXIT_TIME_OUT);
                            setRecorderOptionsEnable(true);
                            Toast.makeText(RecorderActivity.this, getString(R.string.time_out), Toast.LENGTH_SHORT).show();
                        } else {
                            sendEmptyMessageDelayed(MSG_EXIT_TIME_OUT, 1000);
                        }
                        break;

                    //播放成功
                    case MSG_RTSP_PLAY_STATE_SUCCESS:
                        LogUtil.e("llcTest0812", "-------------拉流成功:");
                        mHandler.removeMessages(MSG_RTSP_PLAY_STATE_REPLAY);
                        mRtspPlayReloadNum = 0;
                        //移除重新拉取和超时状态
                        if (loadingIv != null) {
                            loadingIv.setVisibility(View.GONE);
                        }

                        removeRtspMessage();
                        LogUtil.e("llcTest0812", "-----MSG_RTSP_PLAY_STATE_SUCCESS--------isRtspLoading:" + Constant.isRtspLoading);

                        break;

                    case MSG_RTSP_PLAY_STATE_FAIL:
                        removeRtspMessage();

                        if (loadingIv != null) {
                            loadingIv.setVisibility(View.VISIBLE);
                        }
                        RtspPlayer.getInstance().stopPlay(new RtspPlayer.OnPlayStoppedListener() {
                            @Override
                            public void playStopped() {
                            }
                        });

                        mRtspPlayReloadNum++;
                        LogUtil.e("llcTest0812", "-------------重新" + mRtspPlayReloadNum + "次拉流");
                        if (mRtspPlayReloadNum <= 10) {
                            mHandler.sendEmptyMessageDelayed(MSG_RTSP_PLAY_STATE_REPLAY, 1000);
                        }
                        break;

                    //准备播放
                    case MSG_RTSP_PLAY_STATE_READY_PLAY:
                        removeRtspMessage();
                        LogUtil.e("llcTest0812", "-------------准备播放:");
                        mRtspPlayReloadNum = 0;
                        if (loadingIv != null) {
                            loadingIv.setVisibility(View.VISIBLE);
                        }

                        if (StringUtils.isEmptyOrNull(playUrl)) {
                            playUrl = ParamManager.CarServerParam.RtspUrl;
                        }
                        LogUtil.e("llcTest0812", "------RtspPlayerJni-------playUrl:"+playUrl);
                        RtspPlayer.getInstance().setPlayUrl(playUrl);
                        RtspPlayer.getInstance().startPlay();
                        sendRtspMessage();
                        break;

                    //重新播放
                    case MSG_RTSP_PLAY_STATE_REPLAY:
                        removeRtspMessage();
                        if (loadingIv != null) {
                            loadingIv.setVisibility(View.VISIBLE);
                        }
                        LogUtil.e("llcTest0812", "-------------重新播放:");
                        LogUtil.e("llcTest0812", "------RtspPlayerJni-------playUrl:"+playUrl);
                        RtspPlayer.getInstance().setPlayUrl(playUrl);
                        RtspPlayer.getInstance().startPlay();
                        sendRtspMessage();
                        break;

                    //暂停播放
                    case MSG_RTSP_PLAY_STATE_STOP:
                        LogUtil.e("llcTest0812", "-------------暂停播放:");
                        mHandler.removeMessages(MSG_RTSP_PLAY_STATE_REPLAY);
                        LogUtil.e("llcTest0812", "-------------移除超时:");
                        removeRtspMessage();
                        RtspPlayer.getInstance().stopPlay();
                        break;

                    //播放超时
                    case MSG_RTSP_PLAY_STATE_TIME_OUT:
                        mPlayTimeOut++;
                        LogUtil.e("llcTest0812", "-----MSG_RTSP_PLAY_STATE_TIME_OUT--------isRtspLoading:" + Constant.isRtspLoading);
                        //设置超时时间为5秒
                        if (Constant.isRtspLoading) {
                            if (mPlayTimeOut > 50*1000000) {
                                RtspPlayer.getInstance().stopPlay(new RtspPlayer.OnPlayStoppedListener() {
                                    @Override
                                    public void playStopped() {
                                    }
                                });
                                LogUtil.e("llcTest0812", "-------------播放超时:");
                                sendEmptyMessage(MSG_RTSP_PLAY_STATE_FAIL);
                            } else {
                                sendEmptyMessageDelayed(MSG_RTSP_PLAY_STATE_TIME_OUT, 1000);
                            }
                        }


                        break;


                    default:
                        break;
                }

                super.handleMessage(msg);
            }
        };


    }

    private void removeRtspMessage() {
        LogUtil.e("llcTest0812", "-------------removeRtspMessage:");
        Constant.isRtspLoading = false;
        mPlayTimeOut = 0;
    }

    private void sendRtspMessage() {
        LogUtil.e("llcTest0812", "-------------sendRtspMessage:");
        Constant.isRtspLoading = true;
        mPlayTimeOut = 0;
        mHandler.sendEmptyMessage(MSG_RTSP_PLAY_STATE_TIME_OUT);
    }

    @Override
    public void initData() {
        ParamManager.CarServerParam.RtspUrl = CarControl.DeviceInfo.rtsp_url;
        ParamManager.CarServerParam.HttpPort = Integer.valueOf(CarControl.DeviceInfo.file_server_port == null ? "80" : CarControl.DeviceInfo.file_server_port);
        ParamManager.CarServerParam.http_base_url = "http://" + MyApplication.IP + ":" + ParamManager.CarServerParam.HttpPort;
        DownLoadManager.getInstance().baseUrl(ParamManager.CarServerParam.http_base_url).setNetwork(SocketUtils.wifiNetwork).settingOk();
        Glide.with(this).load(R.mipmap.loading).into(loadingIv);
        fullScreenOptionLayout.setVisibility(View.VISIBLE);
        exitfullScreenLl.setVisibility(View.VISIBLE);
        setLayoutSize(DeviceInfo.ScreenHeightPixels * 16 / 9, DeviceInfo.ScreenHeightPixels);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(true);
        CarControl.doGetAllSettings(carControlCallback);
        recordingProgress = (int) ((System.currentTimeMillis() - destroyLastTime) / 1000 + recordingProgress);
        if (isSmallVideoRecording && (recordingProgress > 0 && recordingProgress < 12)) {
            showRecordingProgress();
        }
        playUrl = ParamManager.CarServerParam.RtspUrl;
        if (!GpsUtil.isOPen(this)) {
            showGpsDialog();
        }
        try {

            speed = new TrafficInfo(this, mHandler);
            speed.startCalculateNetSpeed(); // 开启网速监测
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Handler mHandler;
    private TrafficInfo speed;

    private void showGpsDialog() {
        dialogUtils.getCustomMessageAlertDialog(this, R.string.location_authorization_alert).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton(getString(R.string.discount), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
            }
        }).show();
    }

    private void setLayoutSize(int width, int height) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) playerRootFl.getLayoutParams();
        lp.width = width;
        lp.height = height;
        RelativeLayout.LayoutParams lp1 = (RelativeLayout.LayoutParams) rlRecorderPlay.getLayoutParams();
        lp1.width = width;
        lp1.height = height;
        playerContainerFl.removeAllViews();
        rtspPlayerView.setView(0, 0, width, height);
        playerContainerFl.addView(rtspPlayerView);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = false;
        if (!CarControl.IsConnected.get()) {
            if (checkUpdatesVersionManager != null) {
                checkUpdatesVersionManager.dismissUpdateDialog();
            }
            if (null != warningDialog && warningDialog.isShowing()) {
                warningDialog.dismiss();
            }
            if (null != warningDialog && !warningDialog.isShowing() && !isDestroyed()) {
                warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
            }
        }
        CarControl.setGuiNotificationHandler(this);
        CarControl.setOnHeartBeatCallBack(this);
        CarControl.doGetSmallRecordStatus(this);
        initSoundRecordingStatus();
        initSoundVolumeStatus();
        soundRecordingVolumeTv.setVisibility(View.GONE);
        CarControl.doGetVideoSettingInfo(carControlCallback);
        CarControl.doGetLiveResolution(carControlCallback);
        if (rtspPlayerViewReady) {
            LogUtil.e("llcTest0812", "--------onResume-----准备播放:");
            mHandler.sendEmptyMessage(MSG_RTSP_PLAY_STATE_READY_PLAY);
        }
    }





    @Override
    protected void onPause() {
        super.onPause();
        isResume = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        mHandler.sendEmptyMessage(MSG_RTSP_PLAY_STATE_STOP);
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        destroyLastTime = System.currentTimeMillis();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        EventBus.getDefault().unregister(this);
        if (trackPlayTimer != null) {
            trackPlayTimer.cancel();
            trackPlayTimer = null;
        }
    }

    @OnClick(R2.id.rl_recorder_play)
    public void showAndHideOption() {
        if (hasBeepSound && soundRecordingVolumeTv.getVisibility() == View.GONE)
            soundRecordingVolumeTv.setVisibility(View.VISIBLE);
        else
            soundRecordingVolumeTv.setVisibility(View.GONE);

        handler.removeCallbacks(hideOptionBtnRunnable);
        handler.postDelayed(hideOptionBtnRunnable, 5000);
    }

    public void showAndHideNotificationOption(String type) {
        tvRecordnotication.setVisibility(View.VISIBLE);
        if (kNoti_open_light.equals(type)) {
            tvRecordnotication.setBackgroundResource(R.mipmap.recording_icon_lamp);
//            PcmPlayer.getInstance().setDefaultParam().playPcmFile(getApplicationContext(), R.raw.openheadlight);
        } else if (kNoti_front_car_move.equals(type)) {
            tvRecordnotication.setBackgroundResource(R.mipmap.recording_icon_starting);
        } else if (kNoti_driver_time_long.equals(type)) {
            tvRecordnotication.setBackgroundResource(R.mipmap.recording_icon_fatigue);
        }


        handler.removeCallbacks(hideOptionNotificatRunnable);
        handler.postDelayed(hideOptionNotificatRunnable, 3000);
    }

    // 需要点击几次 就设置几
    long[] mHits = null;
    private CustomDialog showLogDialog;
    private Boolean pingIp = false;

    public void showLogDialog() {
        if (mHits == null) {
            mHits = new long[10];
        }
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);//把从第二位至最后一位之间的数字复制到第一位至倒数第一位
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();//记录一个时间
        if (SystemClock.uptimeMillis() - mHits[0] <= 2000) {//两秒内连续点击。
            mHits = null;    //这里说明一下，我们在进来以后需要还原状态，否则如果点击过快，第十一次，第十二次 都会不断进来触发该效果。重新开始计数即可
            final StringBuffer logInfo = new StringBuffer();
            try {
                logInfo.append("\n-当前版本 : " + getResources().getText(R.string.app_name) + " V" + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            logInfo.append("\n-手机厂商 : " + DeviceUtils.getDeviceBrand());
            logInfo.append("\n-手机型号 : " + DeviceUtils.getSystemModel());
            logInfo.append("\n-手机运营商 : " + NetUtils.getOperatorName(getApplicationContext()));
            logInfo.append("\n-系统版本 : " + DeviceUtils.getSystemVersion());
            logInfo.append("\n-记录仪版本 : " + CarControl.DeviceInfo.fw_version);
            logInfo.append("\n-记录仪型号 : " + CarControl.DeviceInfo.model);
            logInfo.append("\n-SSID: " + MyApplication.wifiSSID);
            logInfo.append("\n-IP : " + MyApplication.IP);
            logInfo.append("\n-IPHeader : " + MyApplication.IPHeader);
            showLogDialog = new CustomDialog.AlertBuilder(this)
                    .setContentText(logInfo.toString())
                    .setCanceled(true)
                    .setPositiveBtn("", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                            // 将文本内容放到系统剪贴板里。
                            cm.setText(logInfo.toString());
                            Toast.makeText(RecorderActivity.this, "Copy Succeed。", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                        }

                    })
                    .setDialogInOutAnimResId(-2)
                    .setDialogWindowBgDimAcount(0.6f)
                    .setCanceledOnTouchOutside(false)
                    .createShowLogDialog();
            showLogDialog.show();

        }


    }


    @OnClick(R2.id.ll_exit_fullscreen)
    public void exitFullScreen() {
        finish();
    }


    private void prepareRecordSmaillVideo() {
        recordingProgress = 0;
        recorderVideoPb.setProgress(0);
        setRecorderOptionsEnable(false);
    }

    private Timer trackPlayTimer;
    private int recordingMax = 10;

    private void showRecordingProgress() {
        tvUrgent.setVisibility(View.GONE);
        isSmallVideoRecording = true;
        setRecorderOptionsEnable(false);
        recorderVideoPb.setProgressDrawable(getResources().getDrawable(R.drawable.recorder_small_video_recording_progress));
        recorderVideoPb.setVisibility(View.VISIBLE);
        recorderVideoPb.setMax(10);
        if (trackPlayTimer != null) {
            trackPlayTimer.cancel();
            trackPlayTimer = null;
        }
        trackPlayTimer = new Timer();
        trackPlayTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (recordingProgress < recordingMax) {
                    recordingProgress += 1;
                    if (recorderVideoPb != null) {
                        recorderVideoPb.setProgress(recordingProgress);
                    }
                } else {
                    isSmallVideoRecording = false;
                    if (trackPlayTimer != null) {
                        trackPlayTimer.cancel();
                        trackPlayTimer = null;
                    }
                }
            }
        }, 0, 1000);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (recordingProgress >= recordingMax) {
                    recorderVideoPb.setVisibility(View.GONE);
                    setRecorderOptionsEnable(true);
                    isSmallVideoRecording = false;
                }
            }
        }, 15000);

    }

    private boolean isShowSmiall = false;

    private void showUrgentProgress(boolean isShow, int progress, final int mMax) {
        isShowSmiall = isShow;
        if (!isShow) {
            recorderVideoPb.setVisibility(View.GONE);
            tvUrgent.setVisibility(View.GONE);
            return;
        }
        recorderVideoPb.setVisibility(View.VISIBLE);
        recorderVideoPb.setProgressDrawable(getResources().getDrawable(R.drawable.recorder_urgent_recording_progress));
        recorderVideoPb.setMax(mMax);
        mProgress = progress;
        if (trackPlayTimer != null) {
            trackPlayTimer.cancel();
            trackPlayTimer = null;
        }
        trackPlayTimer = new Timer();
        trackPlayTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                int max = mMax;
                if (mProgress < max) {
                    mProgress += 1;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mProgress % 2 == 0 && isShowSmiall) {
                                tvUrgent.setVisibility(View.VISIBLE);
                            } else {
                                tvUrgent.setVisibility(View.GONE);
                            }
                        }
                    });
                    if (recorderVideoPb != null) {
                        recorderVideoPb.setProgress(mProgress);
                    }
                } else {
                    if (trackPlayTimer != null) {
                        trackPlayTimer.cancel();
                        trackPlayTimer = null;
                    }
                }
            }
        }, 0, 1000);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mProgress >= mMax) {
                    recorderVideoPb.setVisibility(View.GONE);
                    setRecorderOptionsEnable(true);
                    isSmallVideoRecording = false;
                }
            }
        }, mMax - progress + 5000);
    }


    @OnClick(R2.id.ll_fullscreen_take_photo)
    public void takePhoto() {
        setRecorderOptionsEnable(false);
        isTimeOut = false;
        mHandler.sendEmptyMessage(MSG_EXIT_TIME_OUT);
        CarControl.doTakePhoto(carControlCallback);
    }

    @OnClick(R2.id.ll_fullscreen_video)
    public void recorderVideo() {
        prepareRecordSmaillVideo();
        isTimeOut = false;
        mHandler.sendEmptyMessage(MSG_EXIT_TIME_OUT);
        CarControl.doRecordShortVideo(carControlCallback);

    }


    @OnClick(R2.id.iv_discount)
    public void discountLink() {
        discountLinkDevices();
    }


    private CustomDialog mDiscountDialog;

    public void discountLinkDevices() {
        if (mDiscountDialog == null) {
            mDiscountDialog = new CustomDialog.AlertBuilder(this)
                    .setContentText(getString(R.string.discount_connect_recorder_hint))
                    .setNegativeBtn(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            CarControl.IsConnected.set(false);
                            CarControl.HeartBeatStop();
                            finish();
                        }
                    })
                    .setPositiveBtn(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).createPromptDialog();
            mDiscountDialog.setCancelable(true);
            mDiscountDialog.setCanceledOnTouchOutside(true);
        }
        mDiscountDialog.show();


    }


    private int downloadType = Constant.DOWNLOAD.TYPE_PHOTO;


    @OnClick(R2.id.iv_sound_mic)
    public void optionSoundIn() {
        if (settingItemMic == null)
            return;
        if (CarSettingGuiHandler.SETTING_ITEM_OPTION_ON.equals(settingItemMic.settingItemValue)) {
            settingItemMic.settingItemValue = CarSettingGuiHandler.SETTING_ITEM_OPTION_OFF;
            soundRecordingMicIv.setImageDrawable(getDrawable(R.mipmap.close_do_sound));
        } else {
            settingItemMic.settingItemValue = CarSettingGuiHandler.SETTING_ITEM_OPTION_ON;
            soundRecordingMicIv.setImageDrawable(getDrawable(R.mipmap.open_do_sound));
        }
        CarControl.doSetSettingItemValue(settingItemMic.settingItemKey, settingItemMic.settingItemValue, null);
    }

    @OnClick(R2.id.tv_sound_volume)
    public void optionSoundVolume() {
        if (settingItemVolume == null)
            return;
        if (CarSettingGuiHandler.SETTING_ITEM_OPTION_ON.equals(settingItemVolume.settingItemValue)) {
            settingItemVolume.settingItemValue = CarSettingGuiHandler.SETTING_ITEM_OPTION_OFF;
            soundRecordingVolumeTv.setBackgroundResource(R.mipmap.recording_icon_sound_close);
        } else {
            settingItemVolume.settingItemValue = CarSettingGuiHandler.SETTING_ITEM_OPTION_ON;
            soundRecordingVolumeTv.setBackgroundResource(R.mipmap.recording_icon_sound_open);
        }
        CarControl.doSetSettingItemValue(settingItemVolume.settingItemKey, settingItemVolume.settingItemValue, null);
    }

    @OnClick(R2.id.iv_setting)
    public void jumpRecorderSetting() {
        rtspPlayerViewReady = false;
        RtspPlayer.getInstance().stopPlay(new RtspPlayer.OnPlayStoppedListener() {
            @Override
            public void playStopped() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ActivityUtils.jumpActivityForResult(RecorderActivity.this, RecorderSettingActivity.class, null, 10002);
                    }
                });
            }
        });
    }

    @OnClick(R2.id.ll_recorder_album)
    public void enterAlbum() {
        rtspPlayerViewReady = false;
        RtspPlayer.getInstance().stopPlay(new RtspPlayer.OnPlayStoppedListener() {
            @Override
            public void playStopped() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ActivityUtils.jumpActivity(RecorderActivity.this, RecorderAlbumActivity.class);
                    }
                });
            }
        });
    }

    private String kNoti_normal_record_start = "normal_record_start";
    private String kNoti_normal_record_end = "normal_record_end";

    private String kNoti_event_record_start = "event_record_start";
    private String kNoti_event_record_end = "event_record_end";
    private String kNoti_open_light = "open_light";
    private String kNoti_front_car_move = "front_car_move";
    private String kNoti_driver_time_long = "driver_time_long";

    @Override
    public void OnNotication(CarControl.NotificationInfo info) {
        LogUtil.e("llcTest", "----------NotificationInfo-----info---:" + info.type);
        if ("rtsp_url".equals(info.type)) {
            ParamManager.CarServerParam.RtspUrl = info.param;
            CarControl.doGetAllSettings(carControlCallback);
            playUrl = info.param;
            LogUtil.e("llcTest0812", "--------OnNotication-----准备播放:");
            if (rtspPlayerViewReady) {
                LogUtil.e("llcTest0812", "--------onResume-----准备播放:");
                mHandler.sendEmptyMessage(MSG_RTSP_PLAY_STATE_READY_PLAY);
            }
        } else if ("take_photo_start".equals(info.type)) {
            setRecorderOptionsEnable(false);
        } else if ("take_photo_end".equals(info.type)) {
            showPhotoThumb(info);
        } else if ("small_video_start".equals(info.type)) {
            prepareRecordSmaillVideo();
        } else if ("small_video_end".equals(info.type)) {
            showSmallVideoThumb(info.param);
        } else if (kNoti_front_car_move.equals(info.type)) {
            showAndHideNotificationOption(info.type);
        } else if (kNoti_driver_time_long.equals(info.type)) {
            showAndHideNotificationOption(info.type);

        } else if (kNoti_open_light.equals(info.type)) {
            showAndHideNotificationOption(info.type);
            //紧急录像-->开始
        } else if (kNoti_event_record_start.equals(info.type)) {
            try {
                int mParam = Integer.parseInt(info.param);
                if (mParam > 0)
                    showUrgentProgress(true, 0, mParam);
            } catch (Exception e) {

            }
            //紧急录像-->结束
        } else if (kNoti_event_record_end.equals(info.type)) {
            showUrgentProgress(false, 0, 0);
        } else if (kNoti_normal_record_start.equals(info.type)) {
            //录像-->开始
//            mVRedDot.setVisibility(View.VISIBLE);
        } else if (kNoti_normal_record_end.equals(info.type)) {
            //录像-->结束
//            mVRedDot.setVisibility(View.GONE);
        }


    }

    private void showSmallVideoThumb(String url) {
        setRecorderOptionsEnable(true);
//        PcmPlayer.getInstance().setDefaultParam().playPcmFile(getApplicationContext(), R.raw.beep_record_stop);
        recorderVideoPb.setVisibility(View.GONE);
//        if (CarControl.DeviceInfo.get_thumb_on_rec == 0) {
        if (true) {
            Toast.makeText(RecorderActivity.this, getString(R.string.video_saved), Toast.LENGTH_SHORT).show();
            return;
        }
        downloadPath = url;
        List<VideoBean> videoBeanList = new ArrayList<>();
        List<Integer> indexList = new ArrayList<>();
        videoBeanList.add(new VideoBean(null, downloadPath, null));
        indexList.add(0);
//        if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
        CarControl.doGetVideoThumbnail(videoBeanList, indexList, this);
//        }
    }

    private void showPhotoThumb(CarControl.NotificationInfo info) {
        CarControl.CommandResponseInfo commandResponseInfo = new CarControl.CommandResponseInfo();
        commandResponseInfo.msg_id = CarControlCommand.CAR_CONTROL_COMMAND_ID_TAKE_PHOTO;
        commandResponseInfo.param = info.param;
        carControlCallback.OnCommandCallback(0, commandResponseInfo);
    }

    @Override
    public void OnThumbnailGetted(int index) {
        if (!isDestroyed()) {

            if (downloadPath.endsWith(".MP4")) {
                Toast.makeText(RecorderActivity.this, getString(R.string.video_saved), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            downloadCancel();
        }
        return false;
    }

    private void downloadCancel() {
        if (downloadSub != null)
            downloadSub.unsubscribe();
        new File(DownLoadManager.getInstance().getDownloadPathByRemotePath(downloadType, downloadPath)).delete();
    }

    @Override
    public void onClick(View v) {
        warningDialog.dismiss();
        finish();
    }


    @Override
    public void playStarted(int error_code) {
        LogUtil.e("llcTest0812", "-------playStarted------error_code:"+error_code);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (error_code == 0) {
                    mHandler.sendEmptyMessage(MSG_RTSP_PLAY_STATE_SUCCESS);
                } else {
                    mHandler.sendEmptyMessage(MSG_RTSP_PLAY_STATE_FAIL);
                }

            }
        });
    }

    @Override
    public void onRtspPlayerViewSurfaceCreated() {
        if (rtspPlayerViewReady) {
            return;
        }
        LogUtil.e("llcTest0812", "--------onRtspPlayerViewSurfaceCreated-----准备播放:");
        rtspPlayerViewReady = true;
        mHandler.sendEmptyMessage(MSG_RTSP_PLAY_STATE_READY_PLAY);
    }

    @Override
    public void onRtspPlayerViewSurfaceChanged() {
        if (!rtspPlayerViewReady) {
            rtspPlayerViewReady = true;
            LogUtil.e("llcTest0812", "--------onRtspPlayerViewSurfaceChanged-----准备播放:");
            mHandler.sendEmptyMessage(MSG_RTSP_PLAY_STATE_READY_PLAY);
        }

    }

    @Override
    public void OnCommandCallback(int code, CarControl.CommandResponseInfo info) {
        LogUtil.e("llcTest", "--------------OnCommandCallback----:" + info.toString());
        if (code != 0)
            return;
        switch (info.msg_id) {
            //获取当前短视频状态
            case CarControlCommand.APPHTTP_CONTROL_ID_GET_SMALL_RECORD_STATUS:
                LogUtil.e("llcTest", "--------------APPHTTP_CONTROL_ID_GET_SMALL_RECORD_STATUS----:" + info.toString());
                LogUtil.e("llcTest", "--------------APPHTTP_CONTROL_ID_GET_SMALL_RECORD_STATUS----:" + info.event_param);
                if (!TextUtils.isEmpty(info.event_param)) {
                    int[] param = UIUtil.getEeventParam(info.event_param);
                    if (param[0] > 0 && param[1] > 0) {
                        if (param[0] < param[1])
//                            mVRedDot.setVisibility(View.GONE);
                            showUrgentProgress(true, param[0], param[1]);
                    }
                }
                break;

        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                CarControl.doGetVideoSettingInfo(carControlCallback);
            }
        }, 6000);
    }

    class CarControlCallback implements CarControl.OnCarControlCallback {
        @Override
        public void OnCommandCallback(int code, CarControl.CommandResponseInfo info) {
            LogUtil.e("llcTest", "---------CommandResponseInfo-----info----:" + info.toString());
            if (code < 0 || isDestroyed())
                return;
            switch (info.msg_id) {
                case CarControlCommand.CAR_CONTROL_COMMAND_ID_TAKE_PHOTO:
                    mHandler.removeMessages(MSG_EXIT_TIME_OUT);
                    if (isTimeOut) {
                        return;
                    }
                    setRecorderOptionsEnable(true);
                    if (info.rval < 0) {
                        if (info.rval == -31) {
                            Toast.makeText(RecorderActivity.this, getString(R.string.recorder_no_sd_card), Toast.LENGTH_SHORT).show();
                        } else if (info.rval == -32) {
                            Toast.makeText(RecorderActivity.this, getString(R.string.recorder_format_error_sd_card), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(RecorderActivity.this, getString(R.string.take_photo_fail), Toast.LENGTH_SHORT).show();
                        }
                        break;
                    }
//                    PcmPlayer.getInstance().setDefaultParam().playPcmFile(getApplicationContext(), R.raw.beep_take_photo);

//                    if (CarControl.DeviceInfo.get_thumb_on_rec==0) {
                    if (true) {
                        Toast.makeText(RecorderActivity.this, getString(R.string.photo_saved), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    downloadPath = info.param;
                    downloadType = Constant.DOWNLOAD.TYPE_PHOTO;
                    download(Constant.DOWNLOAD.TYPE_PHOTO);
                    List<PhotoBean> photoBeanList = new ArrayList<>();
                    List<Integer> indexList = new ArrayList<>();
                    photoBeanList.add(new PhotoBean(null, downloadPath, null));
                    indexList.add(0);
                    if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                        CarControl.doGetPhotoThumbnail(photoBeanList, indexList, RecorderActivity.this);
                    }
                    break;
                case CarControlCommand.CAR_CONTROL_COMMAND_ID_RECORD_SMALL_VIDEO:
                    if (isTimeOut) {
                        return;
                    }
                    mHandler.removeMessages(MSG_EXIT_TIME_OUT);
                    if (info.rval < 0) {
                        isSmallVideoRecording = false;
                        setRecorderOptionsEnable(true);
                        if (info.rval == -31) {
                            Toast.makeText(RecorderActivity.this, getString(R.string.recorder_no_sd_card), Toast.LENGTH_SHORT).show();
                        } else if (info.rval == -32) {
                            Toast.makeText(RecorderActivity.this, getString(R.string.recorder_format_error_sd_card), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(RecorderActivity.this, getString(R.string.record_small_video_fail), Toast.LENGTH_SHORT).show();
                        }
                        break;
                    }
//                    PcmPlayer.getInstance().setDefaultParam().playPcmFile(getApplicationContext(), R.raw.beep_record_start);
                    showRecordingProgress();
                    break;
                case CarControlCommand.CAR_CONTROL_COMMAND_ID_GET_ALL_SETTINGS:
                    CarControlSettings.parseAllSettings(info.param);
                    setTime();
                    addSystemSetting();
                    addWifiSetting();
                    addRecorderMsgSetting();
                    initSoundRecordingStatus();
                    initSoundVolumeStatus();
                    CarControl.doGetSdCardSpace(carControlCallback);
                    EventBus.getDefault().post(new ScreenDisplayEvent());

                    break;
                case CarControlCommand.CAR_CONTROL_COMMAND_GET_CARD_SPACE:
                    if (CarControlSettings.getAllSettingItems().size() > 0) {
                        CarControlSettings.SettingItem settingItem = CarControlSettings.getSettingItem(CarSettingGuiHandler.SETTING_ITEM_SD_CARD_SIZE);
                        if (null != settingItem)
                            settingItem.settingItemValue = info.param;
                    }
                    break;

                case CarControlCommand.CAR_CONTROL_COMMAND_ID_STOP_RTSP:

                    break;


                case CarControlCommand.APPHTTP_CONTROL_ID_GET_LIVE_RESOLUTION:
                    if (info.rval == 0 && !StringUtils.isEmptyOrNull(info.param)) {
                        try {
                            int mClarity = Integer.parseInt(info.param);
                            if (mClarity == 0 || mClarity == 1 || mClarity == 2) {
                                mCurrentClarity = mClarity;
                                setRecorderClarity();
                            }

                        } catch (Exception e) {
                        }

                    }

                    break;

                case CarControlCommand.APPHTTP_CONTROL_ID_SET_LIVE_RESOLUTION:

                    if (isToggleTimeOut) {
                        return;
                    }
                    mHandler.removeMessages(MSG_TOGGLE_SHARPNESS_TIME_OUT);
                    if (info.rval == 0){
                        LogUtil.e("llcTest0828", "---------111----:" + info.toString());
                        mCurrentClarity = mTmpClarity;
                    }
                    setRecorderClarity();
                    mHandler.sendEmptyMessage(MSG_RTSP_PLAY_STATE_REPLAY);


                    break;


                default:
                    break;
            }
        }
    }

    private int mCurrentClarity = -1;
    private int mTmpClarity = -1;




    private void setRecorderClarity() {
        LogUtil.e("llcTest0828", "---------setRecorderClarity----mCurrentClarity:"+mCurrentClarity );
        if (mCurrentClarity >= 0) {
            llRecorderClarity.setVisibility(View.VISIBLE);
            if (mCurrentClarity==0){
                tveRcorderClarityHigh.setTextColor(getResources().getColor(R.color.recorder_divide));
                tveRcorderClarityMedium.setTextColor(getResources().getColor(R.color.recorder_divide));
                tveRcorderClarityLow.setTextColor(getResources().getColor(R.color.white));
            }else if (mCurrentClarity==1){
                tveRcorderClarityHigh.setTextColor(getResources().getColor(R.color.recorder_divide));
                tveRcorderClarityMedium.setTextColor(getResources().getColor(R.color.white));
                tveRcorderClarityLow.setTextColor(getResources().getColor(R.color.recorder_divide));
            }else{
                tveRcorderClarityHigh.setTextColor(getResources().getColor(R.color.white));
                tveRcorderClarityMedium.setTextColor(getResources().getColor(R.color.recorder_divide));
                tveRcorderClarityLow.setTextColor(getResources().getColor(R.color.recorder_divide));
            }

        } else {
            llRecorderClarity.setVisibility(View.GONE);
        }

    }

    @OnClick(R2.id.tv_recorder_clarity_high)
    public void setRcorderClarityHigh() {
        LogUtil.e("llcTest0828", "---------setRcorderClarityHigh----mCurrentClarity:" +mCurrentClarity);
        if (mCurrentClarity == 2) {
            return;
        }
        toggleTimeOut=0;
        isToggleTimeOut = false;
        mHandler.sendEmptyMessage(MSG_TOGGLE_SHARPNESS_TIME_OUT);
        RtspPlayer.getInstance().stopPlay(new RtspPlayer.OnPlayStoppedListener() {
            @Override
            public void playStopped() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loadingIv != null) {
                            loadingIv.setVisibility(View.VISIBLE);
                        }
                        mTmpClarity = 2;
                        tveRcorderClarityHigh.setTextColor(getResources().getColor(R.color.white));
                        tveRcorderClarityMedium.setTextColor(getResources().getColor(R.color.recorder_divide));
                        tveRcorderClarityLow.setTextColor(getResources().getColor(R.color.recorder_divide));
                        CarControl.doSetLiveResolution("2", carControlCallback);
                    }
                });

            }
        });

    }

    @OnClick(R2.id.tv_recorder_clarity_medium)
    public void setRcorderClarityMedium() {
        LogUtil.e("llcTest0828", "---------setRcorderClarityMedium----mCurrentClarity:" +mCurrentClarity);
        if (mCurrentClarity == 1) {
            return;
        }
        toggleTimeOut=0;
        isToggleTimeOut = false;
        mHandler.sendEmptyMessage(MSG_TOGGLE_SHARPNESS_TIME_OUT);
        RtspPlayer.getInstance().stopPlay(new RtspPlayer.OnPlayStoppedListener() {
            @Override
            public void playStopped() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loadingIv != null) {
                            loadingIv.setVisibility(View.VISIBLE);
                        }
                        mTmpClarity = 1;
                        tveRcorderClarityHigh.setTextColor(getResources().getColor(R.color.recorder_divide));
                        tveRcorderClarityMedium.setTextColor(getResources().getColor(R.color.white));
                        tveRcorderClarityLow.setTextColor(getResources().getColor(R.color.recorder_divide));
                        CarControl.doSetLiveResolution("1", carControlCallback);
                    }
                });

            }
        });
    }


    @OnClick(R2.id.tv_recorder_clarity_low)
    public void setRcorderClarityLow() {
        LogUtil.e("llcTest0828", "---------setRcorderClarityLow----mCurrentClarity:" +mCurrentClarity);
        if (mCurrentClarity == 0) {
            return;
        }
        toggleTimeOut=0;
        isToggleTimeOut = false;
        mHandler.sendEmptyMessage(MSG_TOGGLE_SHARPNESS_TIME_OUT);
        RtspPlayer.getInstance().stopPlay(new RtspPlayer.OnPlayStoppedListener() {
            @Override
            public void playStopped() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loadingIv != null) {
                            loadingIv.setVisibility(View.VISIBLE);
                        }
                        mTmpClarity = 0;
                        tveRcorderClarityHigh.setTextColor(getResources().getColor(R.color.recorder_divide));
                        tveRcorderClarityMedium.setTextColor(getResources().getColor(R.color.recorder_divide));
                        tveRcorderClarityLow.setTextColor(getResources().getColor(R.color.white));
                        CarControl.doSetLiveResolution("0", carControlCallback);
                    }
                });

            }
        });
    }


    private CheckUpdatesVersionManager checkUpdatesVersionManager;

    private void checkUpdatesVersion() {
        checkUpdatesVersionManager = new CheckUpdatesVersionManager(this);
        checkUpdatesVersionManager.checkUpdate(CarControl.DeviceInfo.model, CarControl.DeviceInfo.build_time);
    }

    private void initSoundRecordingStatus() {
        settingItemMic = CarControlSettings.getSettingItem(CarSettingGuiHandler.SETTING_ITEM_MIC);
        if (settingItemMic == null || soundRecordingMicIv == null) {
            hasMic = false;
            return;
        } else {
            hasMic = true;
        }
        if (CarSettingGuiHandler.SETTING_ITEM_OPTION_ON.equals(settingItemMic.settingItemValue)) {
            soundRecordingMicIv.setImageDrawable(getDrawable(R.mipmap.open_do_sound));
        } else {
            soundRecordingMicIv.setImageDrawable(getDrawable(R.mipmap.close_do_sound));
        }
    }

    //通过判断记录仪是否拥有BEEP_SOUND参数。如果有则能操作喇叭按钮
    private boolean hasBeepSound = false;
    private boolean hasMic = false;
    private boolean hasRtsp = false;

    private void initSoundVolumeStatus() {
        settingItemVolume = CarControlSettings.getSettingItem(CarSettingGuiHandler.SETTING_ITEM_BEEP_SOUND);
        if (settingItemVolume == null || soundRecordingVolumeTv == null) {
            hasBeepSound = false;
            return;
        } else {
            hasBeepSound = true;
        }

        if (CarSettingGuiHandler.SETTING_ITEM_OPTION_ON.equals(settingItemVolume.settingItemValue)) {
            soundRecordingVolumeTv.setBackgroundResource(R.mipmap.recording_icon_sound_open);
        } else {
            soundRecordingVolumeTv.setBackgroundResource(R.mipmap.recording_icon_sound_close);
        }
    }

    private void addSystemSetting() {

        CarControlSettings.SettingItem s2 = new CarControlSettings.SettingItem();
        s2.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_RESTORE_FACTORY_SETTINGS;
        CarControlSettings.getAllSettingItems().add(s2);
    }

    private void addRecorderMsgSetting() {
        CarControlSettings.SettingItem s6 = new CarControlSettings.SettingItem();
        s6.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_FORMAT_SD_CARD;
        CarControlSettings.SettingItem s = new CarControlSettings.SettingItem();
        s.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_FW_VERSION;
        s.settingItemValue = CarControl.DeviceInfo.fw_version;

        CarControlSettings.SettingItem s3 = new CarControlSettings.SettingItem();
        s3.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_SD_CARD_SIZE;
        s3.settingItemValue = "";
        CarControlSettings.SettingItem s5 = new CarControlSettings.SettingItem();
        s5.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_APP_VERSION;
        try {
            s5.settingItemValue = "V " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        CarControlSettings.getAllSettingItems().add(s3);
        CarControlSettings.getAllSettingItems().add(s6);
        CarControlSettings.getAllSettingItems().add(s);
        CarControlSettings.getAllSettingItems().add(s5);
    }

    private void addWifiSetting() {
        CarControlSettings.SettingItem s = new CarControlSettings.SettingItem();
        s.settingItemKey = CarSettingGuiHandler.SETTING_ITEM_WIFI_PASSWORD_MODIFY;
        s.settingItemValue = "";
        CarControlSettings.getAllSettingItems().add(s);
    }

    private void setTime() {
        CarControlSettings.SettingItem settingItem = CarControlSettings.getSettingItem(CarSettingGuiHandler.SETTING_ITEM_TIME);
        if (settingItem != null) {
            CarControl.doSetSettingItemValue(settingItem.settingItemKey, CarSettingGuiHandler.SETTING_ITEM_TIME_OPTION_AUTO + "," + DateUtils.getDate(new Date(), true, true, true, true, DateUtils.FORMAT_ONE, true).replace(" ", "_"), null);
        }
    }

    private void setRecorderOptionsEnable(boolean enable) {
        recorderAlbumTv.setEnabled(enable);
        fullscreenVideoTv.setEnabled(enable);
        fullscreenTakePhotoTv.setEnabled(enable);
        if (enable) {
            fullscreenTakePhotoTv.setBackgroundResource(R.mipmap.take_photo);
            fullscreenVideoTv.setBackgroundResource(R.mipmap.record_small_video);
            recorderAlbumTv.setBackgroundResource(R.mipmap.recorder_album);
        } else {
            fullscreenTakePhotoTv.setBackgroundResource(R.mipmap.take_photo_disable);
            fullscreenVideoTv.setBackgroundResource(R.mipmap.record_small_video_disable);
            recorderAlbumTv.setBackgroundResource(R.mipmap.recorder_album_disable);
        }
    }

    @Override
    public void OnHeartBeatConnectOK() {
    }

    @Override
    public void OnHeartBeatConnectFail() {
    }

    @Override
    public void OnHeartBeatDisconnect() {
        mHandler.sendEmptyMessage(MSG_RTSP_PLAY_STATE_STOP);
        if (checkUpdatesVersionManager != null) {
            checkUpdatesVersionManager.dismissUpdateDialog();
        }
        if (!isDestroyed()) {
            //停留0.5s钟等待  等待view加载完毕
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != warningDialog)
                        warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
                }
            }, 500);

        }
    }

    private void download(int type) {
        if (downloadPath == null)
            return;

        if (downloadPath.endsWith(".MP4")) {
            progressDialog.setMessage(downloadPath.substring(downloadPath.lastIndexOf("/") + 1, downloadPath.length()));
            progressDialog.show();
        }
        downloadSub = DownLoadManager.getInstance().download(downloadPath, DownLoadManager.getInstance().getDownloadPathByRemotePath(type, downloadPath), recorderDownloadCallBack);
    }

    public class RecorderDownloadCallBack extends DownLoadCallBack {

        @Override
        public void onCancel() {
        }

        @Override
        public void onCompleted(String path, Uri uri) {
            progressDialog.setProgress(0);
            progressDialog.dismiss();
            if (downloadPath.endsWith(".MP4")) {
                saveMediaInfoToVideoThumb(downloadPath, uri);
            } else {
                CacheManager.saveMediaInfoToExif(CacheManager.getMediaInfoFromExif(CacheManager.getCachePath(downloadPath)), path);
            }
            Toast.makeText(RecorderActivity.this, getString(R.string.photo_saved), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(String e) {
            LogUtil.e(TAG, "-----------RecorderDownloadCallBack---onError--:" + e);
            progressDialog.dismiss();
        }

        @Override
        public void onProgress(long fileSizeDownloaded, long totalSize) {
            progressDialog.setProgress((int) (fileSizeDownloaded * 100 / totalSize));
        }
    }


    public void saveMediaInfoToVideoThumb(final String downloadPath, Uri uri) {
        ContentValues c = new ContentValues();
        LogUtil.e("llcTest", "-----------222222222--:" + CacheManager.getMediaInfoFromExif(CacheManager.getCachePath(downloadPath)).toString());
        c.put(MediaStore.Video.Media.TAGS, CacheManager.getMediaInfoFromExif(CacheManager.getCachePath(downloadPath)).toString());
        getContentResolver().update(uri, c, null, null);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DestroyMapEvent event) {
    }


    class HideOptionBtnRunnable implements Runnable {

        @Override
        public void run() {
//            soundRecordingMicTv.setVisibility(View.GONE);
//            RtspTv.setVisibility(View.GONE);
            soundRecordingVolumeTv.setVisibility(View.GONE);
        }
    }

    class HideOptionNotificatRunnable implements Runnable {

        @Override
        public void run() {
            tvRecordnotication.setVisibility(View.GONE);
        }
    }


}
